/**
 * Created by a1 on 16/10/19.
 */



(function($){
    init()
})(jQuery)


var pageType = $(document.body).attr("pt") //根据pageType区分是人工客服还是智能客服:1->智能 2->人工
var _iScrollPanel
var _iScroll
var nodeList

var heightInput = 0
//FIXME:测试用
var index = 1

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false)

function init() {
    //pageType
    pageType = $(document.body).attr("pt")
    if(pageType=="2") {
        initEmoji()
    }

    _iScroll = new IScroll("#wrapper",{
        mouseWheel: true,
        click: true,
    })
    nodeList = $("#dm_list")

    _iScrollPanel = new IScroll("#wrapper_panel",{
        mouseWheel: true,
        click: true,
    })
    _iScrollPanel.disable()

    //点击隐藏底部面板
    $("#wrapper").click(function(){
        console.log("click")
        hidePanelOP()
        hidePanelEmoji()
    })

    $("#dm_btn_send").hide()
    $("#dm_btn_send").click(function(){
        _onSendText()
    })
    heightInput = $("#dm_input").height()

    //test()
    var imageUrl = "http://img.mp.itc.cn/upload/20161017/1686307d42b24cdf9c5aab2a3d8711ae_th.jpeg"
    var imageUrl2 = "http://img.xiami.net/images/collect_pic/12-14/1387007026_qtKB.jpg"
    //testReceiveImage(image)
    //testReceiveText()
    //alertEvaluate()
    //testReceiveFile("单据下载", imageUrl)
    //testReceiveFileList(["单据下载","单据下载2","单据下载3"], [imageUrl,imageUrl2,imageUrl])
}

//初始话表情
function initEmoji() {
    var node = $("#dm_panel_bottom_emoji")
    for(var i = 0; i < 4; ++i) {
        var row = $("<tr></tr>")
        for(var j = 0; j < 8; ++j) {
            var item = $("<td class='dm_panel_bottom_emoji_item' onclick='onPanelEmojiItemClicked(this)'><img src='../image/emoji/" + (i * 8 + j + 1) + ".gif'></td>")
            row.append(item)
        }
        node.append(row)
    }
    var offset = $(".dm_footer").width() - node.width()
    if(offset > 0){
        node.css("left", (offset * 0.5)+"px")
    }
}
//发送文本
function sendText(text) {
    console.log("text = " + text)
    if(text.length == 0) {
        return
    }
    addDom(false, text)
    if(index > 10) {
        alertEvaluate()
    }
}
//发送图片
function sendImage(imageUrl) {
    var text = _createContentImage(imageUrl)
    addDom(false, text, null, 2)
}
//接收文本
function receiveText(text) {
    addDom(true, text)
}
//接收图片
function receiveImage(text) {
    addDom(true,text,null,2)
}
//创建图片html
function _createContentImage(imageUrl) {
    return "<div class='dm_dialog_content_container_image'><img src='" + imageUrl + "'></div>"
}
//创建文件html
function _createContentFile(fileName, filePath) {
    //return "<a value='" + filePath + "' href='shlb://download?{\"link\":\"" +filePath +"\"}'>" + fileName + "</a>";
    return "<a onclick='onDialogFileClicked(this)' value='" + filePath + "'>" + fileName + "</a>";
}

//监听input
function onKeyDown(event){
    if(event.keyCode == 13) {
        event.preventDefault()
    }
}
function onKeyUp(event){
    if(event.keyCode == 13) {
        _onSendText()
        event.preventDefault()
    }
}
function onInput(){
    var self = $("#dm_input")
    var newHeight = self.height()
    if(newHeight != heightInput) {
        $(".dm_footer").height(26 + self.height())
        heightInput = newHeight
    }
    self.scrollTop(self[0].scrollHeight)
    if(self.html().length > 0){
        $("#dm_btn_send").show()
    }else {
        $("#dm_btn_send").hide()
    }
}
function _onSendText() {
    var nodeInput = $("#dm_input")
    var text = nodeInput.html()
    sendText(text)
    hidePanelEmoji()
    nodeInput.html("")
    onInput()
}
//点击电话
function onCallClicked(){
    dm_alert("拨打银华客服热线","400-678-3333","拨打",function(){
        console.log("拨打电话")
        window.location.href = 'shlb://dialog?{"n":4006783333}'
    },"取消")
}

//点击加号
//显示/隐藏底部操作面板
function onMoreClicked() {
    var footer = $(".dm_footer")
    if(footer.hasClass("dm_show_panel_op")) {
        hidePanelOP()
    }else {
        showPanelOP()
    }
}
//显示底部操作面板
function showPanelOP() {
    hidePanelEmoji()
    $("#dm_panel_bottom_emoji").hide()

    var panel = $("#dm_panel_bottom_op")
    panel.show()
    panel.addClass("dm_show")
    $(".dm_footer").addClass("dm_show_panel_op")
    var wrapper = $("#wrapper")
    wrapper.addClass("dm_anim_transition")
    wrapper.addClass("dm_show_panel_op")
    setTimeout(function(){
        _iScroll.refresh()
    },500)
}
//隐藏底部操作面板
function hidePanelOP() {
    $(".dm_footer").removeClass("dm_show_panel_op")
    $("#dm_panel_bottom_op").removeClass("dm_show")
    var wrapper = $("#wrapper")
    wrapper.removeClass("dm_anim_transition")
    wrapper.removeClass("dm_show_panel_op")
    _iScroll.refresh()
}
//点击底部操作面板上的按钮
function onPanelOPItemClicked(sender) {
    hidePanelOP()
    var this_id = $(sender).attr("id")
    console.log("id ===== " + this_id)
    if(this_id == "dm_btn_download"){
        sendText("单据下载")
        testReceiveFile("文件1","http://img.mp.itc.cn/upload/20161017/1686307d42b24cdf9c5aab2a3d8711ae_th.jpeg")
    }
}
//从本地读取图片并显示
function onBrowerFile(sender){
    var file = sender.files[0]
    if(!/image\/\w+/.test(file.type)){
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(){
        sendImage(this.result)
    }
}

//点击表情
//显示/隐藏表情面板
function onEmojiClicked() {
    var footer = $(".dm_footer")
    if(footer.hasClass("dm_show_panel_emoji")) {
        hidePanelEmoji()
    }else {
        showPanelEmoji()
    }
}

//显示底部表情面板
function showPanelEmoji() {
    hidePanelOP()

    $("#dm_panel_bottom_op").hide()
    var panel = $("#dm_panel_bottom_emoji")
    panel.show()
    panel.addClass("dm_show")

    $(".dm_footer").addClass("dm_show_panel_emoji")
    var wrapper = $("#wrapper")
    wrapper.addClass("dm_anim_transition")
    wrapper.addClass("dm_show_panel_emoji")
    setTimeout(function(){
        _iScroll.refresh()
    },500)
}

//隐藏底部表情面板
function hidePanelEmoji() {
    $(".dm_footer").removeClass("dm_show_panel_emoji")
    $("#dm_panel_bottom_emoji").removeClass("dm_show")
    var wrapper = $("#wrapper")
    wrapper.removeClass("dm_anim_transition")
    wrapper.removeClass("dm_show_panel_emoji")
    _iScroll.refresh()
}

//点击底部面表情板上的按钮
function onPanelEmojiItemClicked(sender) {
    //hidePanelEmoji()
    //var this_id = $(sender).attr("id")
    var nodeInput = $("#dm_input")
    var value = nodeInput.html()
    value += $(sender).html()
    nodeInput.html(value)
    onInput()
}

//点击聊天记录中的图片
function onDialogClicked(sender){
    var src = sender.find(".dm_dialog_content_container_image img").attr("src")
    console.log("src = " + src)
    if(!isEmpty(src)) {
        _showPanelImage(src)
    }
}
//点击聊天记录中的文件下载链接
function onDialogFileClicked(sender) {
    var src = $(sender).attr("value")
    console.log("src = " + src)
    if(!isEmpty(src)) {
        _showPanelImage(src)
    }
}

//点击panel隐藏
function onPanelClicked() {
    _hidePanelImage()
}

//展示大图
function _showPanelImage(src) {
    _iScroll.disable()
    _iScrollPanel.enable()
    $(".dm_panel").show()
    $("#dm_panel_content_image").attr("src", src)
    $("#dm_panel_content_button").attr("href", 'shlb://download?{"link":"'+ src +'"}')
}
//隐藏大图
function _hidePanelImage() {
    _iScroll.enable()
    _iScrollPanel.disable()
    _iScrollPanel.scrollTo(0,0,0)
    $(".dm_panel").hide()
    $("#dm_panel_content_image").attr("src", "")
}

//监听DOM加载完毕
function onDOMLoaded(sender) {
    var self = $(sender)
    var id = self.attr("id")
    console.log("id = " + id)
    if(id == "dm_panel_content_image"){
        _iScrollPanel.refresh()
        var parentHeight = $(".dm_panel").height()
        var height = self.height()
        if(parentHeight > height) {
            self.css("margin-top",((parentHeight - height) * 0.5) + "px")
        }
    }
}

//tType 内容类型
//tType==2表示图片
function addDom(isLeft, text, date, tType) {
    console.log("addDom isLeft = " + isLeft + ", text = " + text + ", type = " + tType)
    var item = $("<div class='dm_dialog'></div>")
    var name = ""
    var avatar = ""
    var arrow = ""
    if(isLeft) {
        item.addClass("dm_dialog_left")
        name = "客服人员"
        avatar = "../image/avatar.png"
        arrow = "../image/arrow_left" + pageType + ".svg"
    }else {
        item.addClass("dm_dialog_right")
        name = "我"
        avatar = "../image/user"+pageType+".jpg"
        arrow = "../image/arrow_right" + pageType + ".svg"
    }
    if(isEmpty(date)) {
        date = dateNow()
    }
    var containerAvatar = $("<div class='dm_dialog_container_avatar'>" +
        "<img src=" + avatar+ ">" +
        "<span>"+ name +"</span></div>")
    var containerContent = $("<div class='dm_dialog_container_content'><div class='dm_dialog_content_date'>"
        + date +
        "</div></div>")
    var content = $("<div class='dm_dialog_content_text'>"
        + text +
        "</div>")
    var arrow = $("<img class='dm_dialog_arrow' src='" + arrow + "'>")
    containerContent.append(arrow)
    if(pageType=="2"){
        console.log("attr")
        containerContent.attr("pt","2")
    }
    if(tType == 2){
        containerContent.click(function(){
            onDialogClicked(containerContent)
        })
        content.addClass("dm_align_center")
    }
    containerContent.append(content)
    item.append(containerAvatar)
    item.append(containerContent)
    nodeList.append(item)
    item.height(Math.max(containerAvatar.height(), (containerContent.height() + 16)))
    //console.log("scrolly = " + _iScroll.y)
    //console.log("maxScrollY = " + _iScroll.maxScrollY)
    var autoBottom = (_iScroll.y == 0 || _iScroll.y < _iScroll.maxScrollY + 10)
    _iScroll.refresh()
    if(autoBottom) {
        _iScroll.scrollTo(0, _iScroll.maxScrollY,400)
    }
}

//展示评价提示
function alertEvaluate(){
    var node = $("<div class='dm_alert'>" +
        "<div class='dm_alert_container'><div class='dm_alert_evalue_top'><img src='../image/beauty.jpg'><div><p>请对此次服务进行评价~</p> " +
        "<form onchange='onRadioChanged(this)'>" +
        "<input type='radio' id='x' name='evalue' value='1'><label for='x'>一般</label> " +
        "<input type='radio' id='y' name='evalue' value='2' checked><label for='y'>满意</label>" +
        "</form>" +
        "</div></div><div class='dm_alert_evalue_middle'><p>您还想对我们说:</p>" +
        "<textarea id='dm_input_evalue' placeholder='意见或建议...'>" +
        "</textarea></div>" +
        "<div class='dm_alert_evalue_bottom'>" +
        "<div onclick='onCommitClicked()'>提交</div>" +
        "<div onclick='onCancelClicked()'>返回聊天</div>" +
        "</div></div></div>")
    $(document.body).append(node)
    node.find(".dm_alert_container").center()
}
//隐藏删除提示
function dismissAlert() {
    $(".dm_alert").remove()
}
//单选框
function onRadioChanged(sender) {
    var value = $(sender).children(":checked").val()
    console.log("checked = " + value)
}
//点击确认
function onCommitClicked() {
    var value = $(".dm_alert_container form").children(":checked").val()
    var text = $("#dm_input_evalue").val()
    console.log("onCommitClicked value = " + value + ", text = " + text)
    dismissAlert()
}
//点击取消
function onCancelClicked() {
    console.log("onCancelClicked")
    dismissAlert()
}

/*
 *FIXME: TEST
 */
function test() {
    console.log("test")
    setTimeout(function(){
        if(index % 3 == 0) {
            testReceiveFile()
        }else if(index % 3 == 1){
            testReceiveImage()
        }else {
            testReceiveText()
        }
        test()
    },2000)
}

function testReceiveText() {
    index++
    var text = "receive text  " + index
    receiveText(text)
}

function testReceiveFile(fileName, filePath) {
    var text = _createContentFile(fileName, filePath)
    receiveText(text)
}

function testReceiveFileList(fileNames, filePaths) {
    var text = "<ul>"
    for(var i = 0; i<fileNames.length; ++i) {
        text += ("<li>" + _createContentFile(fileNames[i], filePaths[i]) + "</li>")
    }
    text += "</ul>"
    receiveText(text)
}

function testReceiveImage(image) {
    var text = "<div class='dm_dialog_content_container_image'><img src='" + image + "'></div>"
    receiveImage(text)
}

